package concurrent.aqs;

import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // 主线程先获取锁，模拟锁被占用
        lock.lock();

        Thread thread = new Thread(() -> {
            System.out.println("子线程尝试获取锁");
            // 获取锁
            lock.lock();
            try {
                System.out.println("子线程获取到锁");
                // 模拟线程执行任务
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("子线程在执行任务时被中断");
            } finally {
                lock.unlock();
            }
        });

        thread.start();

        try {
            // 等待一段时间后中断子线程
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 中断子线程
        System.out.println("主线程尝试中断子线程");
        thread.interrupt();

        try {
            // 主线程休眠一段时间后释放锁
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 主线程释放锁
        System.out.println("主线程释放锁");
        lock.unlock();
    }
}